package com.shanghaionstar.activity;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;

import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.log.LogManager;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.framework.mvp.base.core.AppScheduler;
import com.onstar.cn.framework.utils.RxBus;
import com.onstar.cn.rxconstants.RxConstants;
import com.onstar.cn.sqlite.entities.LandingsPageEntity;
import com.onstar.cn.sqlite.entities.LandingsPageEntityNew;
import com.onstar.cn.sqlite.xutil.exception.DbException;
import com.onstar.cn.vehicle.entity.ErrorEnum;
import com.shanghaionstar.OnstarApplication;
import com.shanghaionstar.service.LandingPageService;

import java.io.File;
import java.util.List;

import rx.functions.Action1;


/**
 * Created by 6335yz on 2016/8/25.
 */
public class LandingPageDLService extends Service {
    private LandingPageService landingPageService;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        landingPageService = new LandingPageService(this);
    }

    LandingsPageEntityNew dbLandingPage;
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        try {
            dbLandingPage = OnstarApplication.getmDbUtils().findFirst(LandingsPageEntityNew.class);
        } catch (DbException e) {
            e.printStackTrace();
        }

//        try {
//            LandingsPageEntity landingsPageEntity = OnstarApplication.getmDbUtils().findFirst(LandingsPageEntity.class);
//            if (landingsPageEntity != null) {
//                File file = new File(landingsPageEntity.getFilePath());
//                if(file.exists()) {
//                    RxBus.getDefault().post(RxConstants.LANDING_PAGE, landingsPageEntity);
//                }else {
//                    deleteLandingPage();
//                }
//            }
//        } catch (DbException e) {
//            e.printStackTrace();
//        }
        landingPageService.
                processDatas(null)
                .subscribeOn(new AppScheduler().backgroundThread())
                .observeOn(new AppScheduler().mainThread())
                .subscribe(new Action1<LandingsPageEntityNew>() {
                    @Override
                    public void call(final LandingsPageEntityNew landingsPageEntity) {
                        landingPageService.setResultListener(new LandingPageService.ResultListener() {
                            @Override
                            public void onSuccess(LandingsPageEntityNew landingPage) {
                                try {
                                    if(dbLandingPage!=null && landingPage!=null && dbLandingPage.getId() != landingPage.getId()) {
                                        deleteLandingPage();
                                    }
                                    OnstarApplication.getmDbUtils().save(landingPage);
                                } catch (DbException e) {
                                    e.printStackTrace();
                                }
                                RxBus.getDefault().post(RxConstants.LANDING_PAGE, landingPage);
//                                try {
//                                    OnstarApplication.getmDbUtils().saveOrUpdate(landingPage);
//                                } catch (DbException e) {
//                                    e.printStackTrace();
//                                }
                                stopSelf();
                            }

                            @Override
                            public void onError(Exception e) {
                                stopSelf();
                            }
                        });
                        LogManager.getInstance().d("the pageid of the landing page is ------>"+landingsPageEntity.getPageId());
                        LogManager.getInstance().d("the id of the landing page is ------>"+landingsPageEntity.getId());
                        landingPageService.downloadImage(landingsPageEntity);
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        if (throwable instanceof OnStarException) {
                            if (ErrorEnum.E2011.getStringValue().equals(((OnStarException) throwable).getErrorCode())) {
                                deleteLandingPage();
                            }
                        }
                        stopSelf();
                    }
                });
        return super.onStartCommand(intent, flags, startId);
    }

    public void deleteLandingPage() {
//        LandingsPageEntity landingPage = landingPageDBService.getLandingPage();
//        if (landingPage != null) {
//            landingPageDBService.delete(landingPage.getId());
//        }
        try {
            List<LandingsPageEntityNew> list = OnstarApplication.getmDbUtils().findAll(LandingsPageEntityNew.class);
            OnstarApplication.getmDbUtils().deleteAll(LandingsPageEntityNew.class);
            if (list != null && list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    CommonUtil.deleteFile(new File(list.get(i).getFileName()));
                }
            }
        } catch (DbException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
